/* jshint esversion: 6 */
import { sequelize } from "./lib/common/initdb"
const Koa = require("koa")
var app = new Koa(),
  logger = require("koa-logger"),
  json = require("koa-json"),
  views = require("koa-views"),
  onerror = require("koa-onerror");

let index = require("./routes/index");
let users = require("./routes/users");
let koajwt = require("koa-jwt")
let jsonwebtoken = require("jsonwebtoken")
const util = require('util');
const {Cfg} = require("./lib/common/config")
const SECRET = Cfg.selfOption.secret;
console.log("------init db-----------", sequelize)

// error handler
onerror(app);

// global middlewares
app.use(
  views("views", {
    root: __dirname + "/views",
    default: "jade",
  })
);
app.use(require("koa-bodyparser")());
app.use(json());
app.use(logger());

app.use(function* (next: any) {
  var start = new Date();
  yield next;
  var ms: number | any;
  ms = (new Date()).getTime() - start.getTime();
  console.log(" %s", ms);
});
// 中间件对token进行验证
app.use(async (ctx:any, next:any) => {
  if(ctx.request.url.indexOf('login') >= 0){
    return next()
  }
  let token = ctx.header.authorization;
  let payload = await util.promisify(jsonwebtoken.verify)(token.split(' ')[1], SECRET);
  return next().catch((err:any) => {
      if (err.status === 401) {
          ctx.status = 401;
          ctx.body = {
            error:{
              code: 401,
              error: err.message
            }
          }
      } else {
          throw err;
      }
  })
});


app.use(koajwt({ secret: SECRET, passthrough: true }).unless({
    // 登录，注册接口不需要验证
    path: [/^\/outapi\/login/]
}));

app.use(require("koa-static")(__dirname + "/public"));

// routes definition
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());

// error-handling
app.on("error", (err: any, ctx: any) => {
  console.error("server error", err, ctx);
});

module.exports = app;
